<!-- 单位编辑弹窗 -->
<template>
  <ele-modal
    v-model="visible"
    :width="640"
    destroy-on-close
    :title="`${data?.name} 库存明细`"
    :bodyStyle="{ paddingTop: '10px' }"
    @opened="reload"
    @close="close"
  >
    <ele-pro-table
      ref="tableRef"
      border
      row-key="id"
      :columns="columns"
      :datasource="datasource"
      :show-overflow-tooltip="true"
      highlight-current-row
      :pagination="false"
      :span-method="spanMethod"
      :height="250"
      :loading="loading"
    >
      <template #type="{ row }">
        <el-tag :type="row.type === 1 ? 'primary' : 'danger'">{{ row.order_type_name }}</el-tag>
      </template>
    </ele-pro-table>
  </ele-modal>
</template>

<script setup>
const props = defineProps({
  data: Object,
})
const visible = defineModel()
/** 表格实例 */
const tableRef = ref(null)

/** 表格列配置 */
const columns = ref([
  {
    type: 'index',
    label: '序',
    width: 44,
    align: 'center',
    fixed: 'left',
  },
  {
    prop: 'warehouse_name',
    label: '仓库',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'location_name',
    label: '库位',
    minWidth: 100,
    align: 'center',
  },
  {
    prop: 'stock',
    label: '库存',
    minWidth: 100,
    align: 'center',
  },
])

const datasource = ref([])

const loading = ref(false)

async function reload() {
  loading.value = true
  const res = await utils.get('/product/stockInfo', { id: props.data.id })
  datasource.value = res.data.reduce((acc, cur) => {
    if (cur.location?.length) {
      cur.location.forEach((v) => {
        acc.push({
          id: `${cur.warehouse_id}-${v.location_id}`,
          warehouse_id: cur.warehouse_id,
          warehouse_name: cur.warehouse_name,
          ...v,
        })
      })
    }
    return acc
  }, [])
  loading.value = false
}

function close() {
  datasource.value = []
}

const spanArr = computed(() => {
  const arr = []
  let pos = 0
  for (let i = 0; i < datasource.value.length; i++) {
    if (i === 0) {
      arr.push(1)
      pos = 0
    }
    else {
      // 判断当前元素与上一个元素是否相同  blId
      if (datasource.value[i].warehouse_id === datasource.value[i - 1].warehouse_id) {
        arr[pos] += 1
        arr.push(0)
      }
      else {
        arr.push(1)
        pos = i
      }
    }
  }
  return arr
})

function spanMethod({ rowIndex, columnIndex }) {
  if (columnIndex === 1) {
    const _row = spanArr.value[rowIndex]
    const _col = _row > 0 ? 1 : 0
    return {
      rowspan: _row,
      colspan: _col,
    }
  }
}
</script>
